package com.deyuanyun.pic.pbf.controller;

import com.alibaba.fastjson.JSONObject;
import com.deyuanyun.pic.common.dto.PageJsonBean;
import com.deyuanyun.pic.common.util.DateUtil;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.RequestUtil;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.common.util.ajax.AjaxSupport;
import com.deyuanyun.pic.common.util.poi.ExcelUtil;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.common.util.web.WebUtil;
import com.deyuanyun.pic.pbf.domain.ExternalInspectionVo;
import com.deyuanyun.pic.pbf.domain.PipeBodyDefect;
import com.deyuanyun.pic.pbf.enumeration.AttachmentFileTypeEnum;
import com.deyuanyun.pic.pbf.enumeration.DefectStateEnum;
import com.deyuanyun.pic.pbf.enumeration.ImgCustomType;
import com.deyuanyun.pic.pbf.enumeration.RepairStateEnum;
import com.deyuanyun.pic.pbf.service.FlawStatisticsService;
import com.deyuanyun.pic.pbf.service.PipeBodyDefectService;
import com.deyuanyun.pic.pipe.controller.BaseController;
import com.deyuanyun.pic.pipe.domain.CenterLine;
import com.deyuanyun.pic.pipe.domain.PiggingStructure;
import com.deyuanyun.pic.pipe.service.PiggingStructureService;
import com.deyuanyun.pic.pipe.service.PipeCenterLineService;
import com.deyuanyun.pic.settings.controller.dto.MyFileVO;
import com.deyuanyun.pic.settings.controller.pipe.vo.PipeLocationDTO;
import com.deyuanyun.pic.settings.controller.pipe.vo.PipePositionDTO;
import com.deyuanyun.pic.settings.domain.base.Attachment;
import com.deyuanyun.pic.settings.domain.prvlg.User;
import com.deyuanyun.pic.settings.domain.util.DomainInitUtil;
import com.deyuanyun.pic.settings.service.base.AttachmentService;
import com.deyuanyun.pic.settings.service.pipe.*;
import com.deyuanyun.pic.settings.support.biz.CodeUtil;
import com.deyuanyun.pic.settings.support.utils.ExcelUtils;
import com.deyuanyun.pic.settings.util.DownExcelUtil;
import com.deyuanyun.pic.wf.service.ProcessDefinitionService;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.javassist.compiler.ast.Symbol;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 非内检数据查询控制层
 *
 * @author lijun
 * @date 2016-06-12
 * <p/>
 * History: [修改人][时间][修改描述]
 */

@Controller
@RequestMapping("/pbf/external")
public class ExternalController extends BaseController {

    @Resource
    private PipeBodyDefectService pipeBodyDefectService;
    @Resource
    private AttachmentService attachmentService;
    @Resource
    private ProcessDefinitionService processDefinitionService;
    @Resource
    private PipeCenterLineService pipeCenterLineService;
    @Resource
    private PipeLocationService pipeLocationService;

    /**
     * 初始化非内检页面
     *
     * @param
     * @return
     * @throws
     */
    @RequestMapping("/externalInspection.html")
    public ModelAndView init(HttpServletRequest request, ModelMap model) {

        //得到缺陷状态下拉
        model.addAttribute("defectStates", DefectStateEnum.values());

        return forword("/pbf/noninternal/noninternalList", model);
    }

    /**
     * 根据条件得到非内检数据列表
     *
     * @param
     * @return
     * @throws
     */
    @RequestMapping("/queryData.json")
    @ResponseBody
    public void queryData(HttpServletRequest request, ModelMap model) {
        HashMap<String, Object> param = RequestUtil.parseRequestParamToHashMap(request);

        // 把当前查询的条件和结果集保存到session里面去
        WebUtils.setSessionAttribute(request, "externalParam", param);

        //待审核数量
        int pendingAudit = pipeBodyDefectService.queryCountByState(param);
        //分页
        PageJsonBean jsonBean = new PageJsonBean();
        //列表和详情(不包含图片)
        List<ExternalInspectionVo> list = pipeBodyDefectService.queryData(param);
        jsonBean.setList(list);

        model.addAttribute("defect", jsonBean);
        model.addAttribute("pendingAudit", pendingAudit);

        AjaxSupport.sendSuccessText("success", model);
    }

    /**
     * 点击详情后得到缺陷id对应的附件图片
     */
    @RequestMapping("/queryImage.json")
    @ResponseBody
    public void queryImage(String id, ModelMap model) {

        if (id != null && !"".equals(id)) {

            List image = attachmentService.queryAttachmentByCustom(id, ImgCustomType.UPLOAD_IMAGE.toString());
            model.addAttribute("image", image);
            AjaxSupport.sendSuccessText("success", model);
        } else {
            AjaxSupport.sendFailText("fail", "");
        }
    }

    /**
     * 导出非内检数据列表
     */
    @RequestMapping("/queryDataExl.json")
    @ResponseBody
    public void queryDataExl(HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {

        HashMap param = RequestUtil.parseRequestParamToHashMap(request);
        List<String[]> result = pipeBodyDefectService.queryDataExport(param);
        String filePath = "/template/excl/pbf/externalInspection.xlsx";
        Workbook externalDefect = ExcelUtil.initWorkbook(filePath, result, 3);
        String nowDate = DateUtil.DateToStringYMd(new Date());
        DownExcelUtil.fillWorkbookHead(externalDefect);
        WebUtil.setDownHeader("非内检测缺陷"+nowDate+".xlsx");
        externalDefect.write(response.getOutputStream());
    }


    /**
     * @param @param ids id数组
     * @return void
     * @Description: 非内检缺陷数据删除/批量删除
     */
    @RequestMapping("/updateTodelete.json")
    @ResponseBody
    public void updateToDelete(@RequestParam(value = "ids", required = false) String[] ids, ModelMap model) {
        int i = 0;
        for (String id : ids) {

            PipeBodyDefect defect = new PipeBodyDefect();
            defect.setId(id);

            i += pipeBodyDefectService.updateToDeleteById(defect);

        }
        model.addAttribute("deletedNum", i);
        if (i == ids.length) {
            AjaxSupport.sendSuccessText("success", model);
        } else if (i < ids.length && i != 0) {
            AjaxSupport.sendSuccessText("partSuccess", model);
        } else if (i == 0) {
            AjaxSupport.sendFailText("fail", model);
        }
    }

    /**
     * 进入审核界面
     *
     * @param id 非内检缺陷信息ID
     * @return
     * @throws
     */
    @RequestMapping("/auditing.html")
    public ModelAndView auditingInit(String id, ModelMap audit) {

        ExternalInspectionVo defect = pipeBodyDefectService.queryDefectById(id);

        if (defect != null) {
            Asserts.assertTrue(!DefectStateEnum.state01.getCode().equals(defect.getState()), "该缺陷点无法审核");
            List image = attachmentService.queryAttachmentByCustom(defect.getId(),ImgCustomType.UPLOAD_IMAGE.toString());
            audit.addAttribute("defect", defect);
            audit.addAttribute("image", image);
        }


        //mav.setViewName("");

        return forword("/pbf/noninternal/noninternalAuditing", audit);

    }

    /**
     * 审核缺陷是否通过
     *
     * @param id 非内检缺陷id
     *           state  缺陷当前状态  --通过则为 已发布   --不通过则是 审核不通过
     *           remark 审核不成功的备注
     * @return 受影响条数
     * @throws
     */
    @RequestMapping("/auditing.json")
    @ResponseBody
    public void auditing(String id, String state, String remark) {

        if (id != null && !"".equals(id)) {

            if (DefectStateEnum.state04.getCode().equals(state) && (remark == null || "".equals(remark))) {
                AjaxSupport.sendFailText("审核不通过，备注不能为空", "");
            }

            PipeBodyDefect record = new PipeBodyDefect();
            record.setId(id);
            record.setDataReasonRejected(remark);
            record.setDataStated(state);
            DomainInitUtil.initUpdateDomain(record);

            int i = pipeBodyDefectService.updateByPrimaryKeySelective(record);

            if (i > 0) {
                AjaxSupport.sendSuccessText("success", "");
            } else {
                AjaxSupport.sendFailText("fail", "");
            }
        } else {
            AjaxSupport.sendFailText("fail", "");
        }
    }

    /**
     * 添加非内检缺陷页面
     */
    @RequestMapping("/create.html")
    public ModelAndView createView(ModelMap model) {

        //修复方法下拉
        model.addAttribute("repairMethods", processDefinitionService.queryProcessName());

        return forword("/pbf/noninternal/noninternalCreate", model);

    }

    /**
     * 新增非内检缺陷
     *
     * @param
     * @return
     * @throws
     */
    @RequestMapping("/create.json")
    @ResponseBody
    public void createPipeBodyDefect(PipeBodyDefect record,
                                     @RequestParam(value = "att", required = false) String att[]) throws Exception {

        int num = pipeBodyDefectService.createPipeBodyDefect(record, att);
        if (num > 0) {

            AjaxSupport.sendSuccessText("success", "");
        } else {
            AjaxSupport.sendFailText("fail", "");
        }
    }

    /**
     * 统计非内检缺陷页面初始化
     */
    @RequestMapping("/statistics.html")
    public ModelAndView queryOtherInspectionBarInit(HttpServletRequest request, ModelMap model) {
        HashMap<String, Object> param = RequestUtil.parseRequestParamToHashMap(request);
        model.addAttribute("param", param);
        return forword("/pbf/noninternal/noninternalStatistics", model);
    }

    /**
     * 统计非内检缺陷
     */
    @RequestMapping("/statistics.json")
    @ResponseBody
    public void queryOtherInspectionBar(HttpServletRequest request) {
        Map<String, Object> param = RequestUtil.parseRequestParamToHashMap(request);
        List<Map<String, Object>> statistics = pipeBodyDefectService.queryOtherInspection(param);
        //统计信息
        AjaxSupport.sendSuccessText("success", statistics);

    }

    /**
     * 根据管道ID查询管道中心线信息
     *
     * @param lineId
     */
    @RequestMapping("/getLineGisId.json")
    @ResponseBody
    public void getLineGisId(@RequestParam("lineId") String lineId) {
        CenterLine centerLine = pipeCenterLineService.getCenterLineByLineId(lineId);
        if (centerLine != null) {
            AjaxSupport.sendSuccessText("success", centerLine);
        } else {
            AjaxSupport.sendFailText("fail", "");
        }
    }

    /**
     * 按附件类型和业务ID删除缺陷检测报告
     */
    @RequestMapping("/delectReport.json")
    @ResponseBody
    public void delectReport(@RequestParam("businessId") String businessId) {
        //判断非内检缺陷检测报告是否已存在
        List<Attachment> list = attachmentService.queryAttachmentByCustom(businessId, "defectInspectionReport");
        if (list.size() != 0) {
            int i = 0;
            for (Attachment a : list) {
                //删除已上传的缺陷检测报告
                i = attachmentService.deleteByPrimaryKey(a.getId());
            }
            if (i > 0) {
                AjaxSupport.sendSuccessText("success", "");
            } else {
                AjaxSupport.sendFailText("fail", "删除失败");
            }
        } else {
            AjaxSupport.sendFailText("fail", "删除失败，缺陷检测报告不存在");
        }

    }

    /**
     * 验证用户填写的绝对距离是否在管道绝对距离区间
     */
    @RequestMapping("/milageValidate.json")
    @ResponseBody
    public boolean milageValidate(@RequestParam("pipeLineId") String pipeLineId,@RequestParam("milage") BigDecimal milage) {
        //得到管道绝对距离区间
        PipePositionDTO pipePositionDTO = pipeLocationService.queryPipeLinePosition(pipeLineId);
        Asserts.assertTrue(ObjectUtil.isNotNullEmpty(pipePositionDTO),"未查询到该管道的对应信息");
        Asserts.assertTrue(null != milage,"未得到缺陷的绝对距离");

        return  milage.compareTo(pipePositionDTO.getBeginMileage()) >= 0 && milage.compareTo(pipePositionDTO.getEndMileage()) <= 0;
    }
    /**
     * 保存缺陷检测报告
     *
     * @param businessId 业务ID
     *                   attId 附件表ID

     @RequestMapping("/uploadReport.json")
     @ResponseBody public void uploadReport(@RequestParam("businessId") String businessId, @RequestParam("attId") String attId) {
     if (businessId != null && !"".equals(businessId)
     && attId != null && !"".equals(attId)) {
     //判断非内检缺陷检测报告是否已存在
     List<Attachment> list = attachmentService.queryAttachmentByCustom(businessId,"defectInspectionReport");
     if(list.size() != 0){
     for(Attachment a:list){

     //删除已上传的附件
     attachmentService.deleteByPrimaryKey(a.getId());
     }
     }
     //保存附件
     attachmentService.updateBusinessIdById(businessId, attId);
     AjaxSupport.sendSuccessText("success","");
     } else {
     AjaxSupport.sendFailText("fail", "");
     }

     } */

}
